package com.example.easynote;

import java.util.Calendar;
import java.util.TimeZone;


import DAO.NotesDAO;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.easynote.UI.AlarmManagerBroadcastReceiver;

@SuppressLint("NewApi")
public class Alarm extends Activity implements OnClickListener, OnCheckedChangeListener {
	private Button btnOK;
	private Button btnCANCEL;
	private Button btnDatePicker;
	private Button btnTimePicker;
	private Switch swtAlarm;
	private int year;
	private int month;
	private int day;
	private int Hour;
	private int Minute;
	
	TextView txtDatePicker;
	TextView txtTimePicker;
	
	static final int DATE_DIALOG_ID = 999;
	static final int TIME_DIALOG_ID = 888;
	
	Calendar cal;
	//sendbroadcast
	private AlarmManagerBroadcastReceiver alarm;

	long rowID=0;
	String title=null;
	String body=null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_alarm);
		
		btnOK = (Button)findViewById(R.id.btnOK);
		btnCANCEL = (Button)findViewById(R.id.btnCANCEL);
		btnDatePicker = (Button)findViewById(R.id.btnDatePicker);
		btnTimePicker = (Button)findViewById(R.id.btnTimePicker);

		txtDatePicker = (TextView)findViewById(R.id.txtDatePicker);
		txtTimePicker = (TextView)findViewById(R.id.txtTimePicker);
		
		swtAlarm = (Switch)findViewById(R.id.swtAlarm);
		
		btnOK.setOnClickListener(this);
		btnCANCEL.setOnClickListener(this);
		btnDatePicker.setOnClickListener(this);
		btnTimePicker.setOnClickListener(this);
		
		swtAlarm.setOnCheckedChangeListener(this);
		
		cal = Calendar.getInstance();
		cal.setTimeInMillis(System.currentTimeMillis());
		cal.setTimeZone(TimeZone.getTimeZone("UTC"));
		
		
		Bundle extras = getIntent().getExtras();
		rowID = extras.getLong(NotesDAO.KEY_ROWID);
		title = extras.getString(NotesDAO.KEY_TITLE);
		body = extras.getString(NotesDAO.KEY_BODY);
		alarm = new AlarmManagerBroadcastReceiver();
		setCurrentDate();
		

		/*
		//gui title va body broadcast
		Intent intent1 = new Intent(this, AlarmManagerBroadcastReceiver.class);
		intent1.putExtra(NotesDAO.KEY_TITLE, title);
		intent1.putExtra(NotesDAO.KEY_BODY, body);
		PendingIntent sender = PendingIntent.getBroadcast(this, 0,
				intent1, PendingIntent.FLAG_UPDATE_CURRENT);
		*/
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	//////////////////////////////////////////////////////////
	
	public void setCurrentDate() {
		final Calendar calendar = Calendar.getInstance();
		year = calendar.get(Calendar.YEAR);
		month = calendar.get(Calendar.MONTH);
		day = calendar.get(Calendar.DAY_OF_MONTH);
	}
	public void setCurrentTime()
	{
		final Calendar c = Calendar.getInstance();
        // Current Hour
        Hour = c.get(Calendar.HOUR_OF_DAY);
        // Current Minute
        Minute = c.get(Calendar.MINUTE);
         
        // set current time into output textview
        updateTime(Hour, Minute);
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
		   // set date picker as current date
		   return new DatePickerDialog(this, datePickerListener, 
                         year, month,day);
		case TIME_DIALOG_ID:
            // set time picker as current time
            return new TimePickerDialog(this, timePickerListener, Hour, Minute,
                    false);
		}
		return null;
	}
 
	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() 
	{
		// when dialog box is closed, below method will be called.
		public void onDateSet(DatePicker view, int selectedYear,int selectedMonth, int selectedDay)
		{
        	year = selectedYear;
        	month = selectedMonth;
        	day = selectedDay;
        	
        	cal.set(Calendar.MONTH,month);
            cal.set(Calendar.YEAR,year);
            cal.set(Calendar.DAY_OF_MONTH,day);
        	
        	// set selected date into Text View
        	txtDatePicker.setText(Integer.toString(month+1)+
        			"/"+Integer.toString(day)+"/"+Integer.toString(year));
        }
	};

	private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
        
		 
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minutes) {
            // TODO Auto-generated method stub
            Hour   = hourOfDay;
            Minute = minutes;
            cal.set(Calendar.MONTH,month);
            cal.set(Calendar.YEAR,year);
            cal.set(Calendar.DAY_OF_MONTH,day);
            
            cal.set(Calendar.HOUR_OF_DAY,Hour);
            cal.set(Calendar.MINUTE,Minute);
            cal.set(Calendar.SECOND,0);
            
            updateTime(Hour,Minute);
             
         }
    };
    // Used to convert 24hr format to 12hr format with AM/PM values
    private void updateTime(int hours, int mins) {
         
        String timeSet = "";
        if (hours > 12) {
            hours -= 12;
            timeSet = "PM";
        } else if (hours == 0) {
            hours += 12;
            timeSet = "AM";
        } else if (hours == 12)
            timeSet = "PM";
        else
            timeSet = "AM";
 
         
        String minutes = "";
        if (mins < 10)
            minutes = "0" + mins;
        else
            minutes = String.valueOf(mins);
 
        // Append in a StringBuilder
         String aTime = new StringBuilder().append(hours).append(':')
                .append(minutes).append(" ").append(timeSet).toString();
 
          txtTimePicker.setText(aTime);
    }
    
    
    
	@SuppressWarnings("deprecation")
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Context context = this.getApplicationContext();
		switch(v.getId())
		{
		case R.id.btnTimePicker:
			showDialog(TIME_DIALOG_ID);
			break;
		case R.id.btnDatePicker:
			showDialog(DATE_DIALOG_ID);
			break;
		case R.id.btnOK:
			
			if (alarm != null) {
				cal.setTimeZone(TimeZone.getTimeZone("UTC"));
				alarm.setOnetimeTimer(context,cal,(int)rowID,title,body);
			} else {
				Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show();
			}
			finish();
			break;
		case R.id.btnCANCEL:
			if (alarm != null) {
				alarm.CancelAlarm(context);
			} else {
				Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show();
			}
			finish();
			break;
		}
	}
	
	public void showNotification(){

		// define sound URI, the sound to be played when there's a notification
		Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
		
		// intent triggered, you can add other intent for other actions
		Intent intent = new Intent(Alarm.this, Alarm.class);
		PendingIntent pIntent = PendingIntent.getActivity(Alarm.this, 0, intent, 0);
		
		// this is it, we'll build the notification!
		// in the addAction method, if you don't want any icon, just set the first param to 0
		Notification mNotification = new Notification.Builder(this)
			
			.setContentTitle("New Post!")
			.setContentText("Here's an awesome update for you!")
			.setSmallIcon(R.drawable.ic_clock)
			.setContentIntent(pIntent)
			.setSound(soundUri)
			
			.addAction(R.drawable.ic_clock, "View", pIntent)
			.addAction(0, "Remind", pIntent)
			
			.build();
		
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		// If you want to hide the notification after it was selected, do the code below
		// myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
		
		notificationManager.notify(0, mNotification);
	}
	
	public void cancelNotification(int notificationId){
		
		if (Context.NOTIFICATION_SERVICE!=null) {
            String ns = Context.NOTIFICATION_SERVICE;
            NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
            nMgr.cancel(notificationId);
        }
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		// TODO Auto-generated method stub
		if(isChecked == true)
		{
			
		}
		else
		{
			
		}
		Toast.makeText(getApplicationContext(), "sdfsdf", Toast.LENGTH_SHORT).show();
	}
}
